//
//  PhotoAlbumViewController.swift
//  EasePods
//
//  Created by 易先生 on 2024/5/22.
//

import UIKit
import Photos
import RxSwift
import RxCocoa
import MoyoungLib

class PhotoAlbumViewController: ViewController {
        
    private var PhotosRelay: BehaviorRelay = BehaviorRelay<[PHAsset]>(value: [])
    
    override func viewDidLoad() {

        super.viewDidLoad()
                
        // 请求照片库访问权限
        PHPhotoLibrary.requestAuthorization { status in
            
            switch status {
            case .authorized:
                self.fetchPhotos()
            case .denied, .restricted:
                // 处理用户拒绝访问
                break
            case .notDetermined:
                // 尚未决定
                break
            case .limited:
                //有限选择
                self.fetchPhotos()
                break
            @unknown default:
                fatalError()
            }

        }
        
    }
    
    func fetchPhotos() {
        // 获取照片
        DispatchQueue.global(qos: .userInitiated).async {
            var potos: [PHAsset] = []
            let fetchOptions = PHFetchOptions()
            fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
            
            let allPhotos = PHAsset.fetchAssets(with: .image, options: fetchOptions)

            allPhotos.enumerateObjects { (asset, index, stop) in
                potos.append(asset)
            }
            
            DispatchQueue.main.async {
                self.PhotosRelay.accept(potos)
                self.title = "\(potos.count)potos"
            }
        }

    }
    
    override func makeUI() {
        super.makeUI()
        self.view.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(kNavHeight+1)
            make.leading.trailing.bottom.equalToSuperview()
        }
    }
    
    override func bindViewModel() {
        super.bindViewModel()
        
        PhotosRelay.bind(to: collectionView.rx.items(cellIdentifier: PhotoAlbumCollectionViewCell.reuseIdentifier, cellType: PhotoAlbumCollectionViewCell.self)) {i, item, cell in
            cell.bind(to: item)
        }.disposed(by: rx.disposeBag)
        
        collectionView.rx.itemSelected.subscribe(onNext: { [weak self] indePath in
            guard let self = self else { return }
            let vc = PhotoAlbumPreviewController()
            self.PhotosRelay.bind(to: vc.PhotosRelay).disposed(by: rx.disposeBag)
            vc.selectIndex = indePath.row
            vc.modalPresentationStyle = .fullScreen
            self.present(vc, animated: true)
        }).disposed(by: rx.disposeBag)
        
    }
    
    private lazy var collectionView: UICollectionView = {
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: flowLayoutView)
        collectionView.backgroundColor = .black
        collectionView.register(PhotoAlbumCollectionViewCell.self, forCellWithReuseIdentifier: PhotoAlbumCollectionViewCell.reuseIdentifier)
        collectionView.showsVerticalScrollIndicator = false
        collectionView.showsHorizontalScrollIndicator = false
        return collectionView
    }()
    
    private lazy var flowLayoutView: UICollectionViewFlowLayout = {
        let width = (UIScreen.main.bounds.width-2)/3
        let height = width
        let flowLayoutView = UICollectionViewFlowLayout()
        flowLayoutView.scrollDirection = .vertical
        flowLayoutView.minimumInteritemSpacing = 1
        flowLayoutView.minimumLineSpacing = 1
        flowLayoutView.itemSize = CGSize(width: width , height: Double(height))
        return flowLayoutView
    }()
    
}
